'use strict'

let URL = 'http://be.yuyucoding.top';

//初始化页面：
$(function () {
    getData();
})

function getData(keyword) {
    let url = 'http://be.yuyucoding.top/blogs';
    let tbBlog = $('#tbBlog');
    let tr = $('[id^="role"]');

    tr.remove();
    if (keyword) {
        url = url + '?keyword=' + keyword;
        // console.log(keyword);
    }
    $.ajax({
        type: 'get',
        url: url,
        success: function (res) {
            // console.log(res);

            res.forEach(element => {
                let html = `
               <tr id="role${element.id}">

               <td>${element.id}</td>
               <td>${element.title}</td>
               <td>${element.content}</td>
               <td> <input type="button" value="编辑" onclick="btnEdit(${element.id})" >
                   <input type="button" value="删除" onclick="btnDel(${element.id})" >
               </td>
           </tr>
               `
                tbBlog.append(html);
            });
        }
    });
}
//获取url？id=5的id参数5的函数
function getParams(name) {
    let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    let r = location.search.substring(1).match(reg);
    if (r != null) {
        return decodeURIComponent(r[2]);
    }
    return null;
}

//查找
function btnFind() {
    //console.log(111);
    let keyword = $('[id="keyword"]').val();
    getData(keyword);
}

//新增
function btnAdd() {
    location.href = 'blogEdit.html';
}

//编辑
function btnEdit(id) {
    location.href = 'blogEdit.html?id=' + id;
}

//删除
function btnDel(id) {
    if (confirm('请问是否删除？')) {
        $.ajax({
            type: 'delete',
            url: URL + '/blogs/' + id,
            success: function (res) {
                //$('#roles ' + id).remove();
                $('#role' + id).remove();
            }
        });
    }
}

//刷新
function btnReFresh() {
        getData();
}